#include <stdlib.h>
#include <string>
#include <iostream>
#include <rise/common/exmacros.h>
#include <rise/common/Log.h>
#include <rise/common/Exception.h>
#include "MessageQueueManager.h"
#include "MQServer.h"

int main(int nArgs, char* szArgs[])
{
  std::string sServerHost = "all";
  unsigned short ushServerPort = 8768;
  int nMaxQueue = 10;
  int nQueueLimit = 100;

  for (int nArg = 1; nArg < nArgs; ++nArg)
  {
    if(szArgs[nArg])
    {
      const std::string& sArg = std::string(szArgs[nArg]);
      if (sArg.substr(0, 2) == "-s")
      {
        sServerHost = sArg.substr(2);
      }
      else
      if (sArg.substr(0, 2) == "-p")
      {
        ushServerPort = static_cast<unsigned short>(atoi(sArg.substr(2).c_str()));
      }
      else
      if (sArg.substr(0, 2) == "-q")
      {
        nMaxQueue = atoi(sArg.substr(2).c_str());
      }
      else
      if (sArg.substr(0, 2) == "-l")
      {
        nQueueLimit = atoi(sArg.substr(2).c_str());
      }
      else
      if (sArg.substr(0, 2) == "-h")
      {
        std::cerr << "Simple message queue server.\n\n"
            << szArgs[0] << " [-h][-s<Server bind host>|all][-p<port>][-q<max socket queue>][-l <queue limit(default: 100)>]\n\n";
        return 0;
      }
      else
      {
        std::cerr << "unknown arg: " << sArg << "\n";
        return 1;
      }
    }
  }

  try
  {
    smq::MessageQueueManager::Inst().SetDefaultQueueLimit(nQueueLimit);
    smq::MQServer::Inst().Start(sServerHost, ushServerPort, nMaxQueue);
    smq::MQServer::FreeInst();
  }
  RISE_CATCH_ALL

  return 0;
}
